
package devicedbgui;


import devicedbgui.data.TestCase;
import devicedbgui.data.Exe;
import devicedbgui.data.TestCaseDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** Displays all test cases */
public class TestCasePanel extends javax.swing.JPanel {
 /** Reference to GUI class for accessing its variables */
    public GUI gui;
    public Exe exe;
    Hashtable<Integer, TestCase> htTestCase = new Hashtable<Integer, TestCase>();
    
    /** Constructor creates all components belonging to panel */   
    public TestCasePanel() {
        initComponents();
    }/** Displays error messages */  
 public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Displays test cases associated with exe */
    public void showTestCases(GUI gui, Exe exe)
    {
        this.gui = gui;
        this.exe=exe;
        TestCaseDAO dd = new TestCaseDAO(gui.connection);
        try {
            ArrayList<TestCase> records = dd.selectByExe(exe.idexe);
            DefaultTableModel model = (DefaultTableModel)tblTestCase.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htTestCase.clear();
            for (TestCase item : records){ 
                htTestCase.put(new Integer(index++), item);
                addRow(model, item);
           }
            
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
/** Adds row to JTable */    
    private void addRow(DefaultTableModel model, TestCase item)    
    {
        model.addRow(new Object[]{item.idTestCase, item.getTestCase(), item.getResult()
                , item.exe_idexe});
    }
    /** Shows all test cases */
    public void showAll(GUI gui)
    {
        this.gui = gui;

        TestCaseDAO dd = new TestCaseDAO(gui.connection);
        try {
            ArrayList<TestCase> records = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblTestCase.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htTestCase.clear();
            for (TestCase item : records){ 
                htTestCase.put(new Integer(index++), item);
                addRow(model, item);
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
     /** Refreshes display of list of test cases in database */
     public void update()
    {
        TestCaseDAO dd = new TestCaseDAO(gui.connection);
        try {
            ArrayList<TestCase> records = null;
            if (exe != null)
                records = dd.selectByExe(exe.idexe);
            else 
                records = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblTestCase.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htTestCase.clear();
            for (TestCase item : records){ 
                htTestCase.put(new Integer(index++), item);
                //model.addRow(new Object[]{item.idTestCase, item.description, item.exe_idexe});
                addRow(model, item);
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
    }
     
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblTestCase = new javax.swing.JTable(){    public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tblTestCase.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblTestCase.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnViewTestResult = new javax.swing.JButton();
    btnAdd = new javax.swing.JButton();
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();

    tblTestCase.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "Test Case ID", "Test Case", "Result", "Exe ID"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblTestCase.setGridColor(new java.awt.Color(204, 204, 255));
    tblTestCase.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(tblTestCase);

    btnViewTestResult.setText("View Test Result");
    btnViewTestResult.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewTestResultActionPerformed(evt);
        }
    });

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                        .addComponent(btnEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                        .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
                    .addGap(18, 18, 18))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(btnViewTestResult, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnViewTestResult});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(btnAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewTestResult))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
            .addContainerGap())
    );
    }// </editor-fold>//GEN-END:initComponents
/** View test results associated with selected test case */
private void btnViewTestResultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewTestResultActionPerformed
int selectedIndex = tblTestCase.getSelectedRow();    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    TestCase item = htTestCase.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setTestCaseID(String.valueOf(item.idTestCase));
    TestResultPanel tr = new TestResultPanel();
    tr.showTestResults(gui, item);
       
    
   gui.tab.add(tr);
   gui.tab.setSelectedComponent(tr); 
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("View Test Results") );
   
}//GEN-LAST:event_btnViewTestResultActionPerformed
/** Add new test case */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditTestCaseDlg dlg = new EditTestCaseDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
/** Edit test case */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblTestCase.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    TestCase item = htTestCase.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    EditTestCaseDlg dlg = new EditTestCaseDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htTestCase.remove(new Integer(selected[0]));        
        htTestCase.put(new Integer(selected[0]), dlg.testCase);
        update();
    }
}//GEN-LAST:event_btnEditActionPerformed
/** Delete selected test case */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblTestCase.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        TestCaseDAO dd = new TestCaseDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                TestCase item = htTestCase.get(new Integer(selected[i]));   
                dd.delete(item.idTestCase);
                htTestCase.remove(new Integer(selected[i]));

            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/** Returns id of current exe file */
public int getExeID()
{return exe.idexe;
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnViewTestResult;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblTestCase;
    // End of variables declaration//GEN-END:variables

}
